package com.baizw.cultivation.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baizw.cultivation.common.annotation.method.OnlyOneMapper;
import com.baizw.cultivation.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 唯一性校验工具类
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年05月20日 18:07
 */
@Slf4j
public class OnlyOneValidUtil {

    public static String verify(String tableName, String key, Object value) {
        if (StrUtil.isNotBlank(tableName)) {
            try {
                Object[] objects = ArrayUtil.isArray(value) ? ArrayUtil.cast(Object.class, value) : new Object[]{value};

                List<Object> dataExistList = SpringUtil.getBean(OnlyOneMapper.class).dataExist(tableName, StrUtil.toUnderlineCase(key), objects);
                Collection<Object> disjunction = CollUtil.disjunction(dataExistList, CollUtil.toList(objects));

                String messageTemplate = "数据【{}】已存在，请核验";
                String messageTemplate1 = "数据【{}】不存在，请核验";
                List<String> collect = dataExistList.parallelStream().map(x -> cn.hutool.core.util.StrUtil.format(messageTemplate, x)).collect(Collectors.toList());
                List<String> collect1 = disjunction.parallelStream().map(x -> cn.hutool.core.util.StrUtil.format(messageTemplate1, x)).collect(Collectors.toList());
                String resultString = Stream.of(collect, collect1).flatMap(List::stream).collect(Collectors.joining(StrUtil.LF));
                return dataExistList.size() > 0 ? resultString : StrUtil.EMPTY;
            } catch (Exception e) {
                log.error("数据库唯一性校验异常", e);
                throw new GlobalException("数据库唯一性校验异常", e);
            }
        }
        return StrUtil.EMPTY;
    }

    /**
     * 校验是否存在
     *
     * @param tableName 表名称
     * @param key       校验字段
     * @param value     参数值
     * @return 是否存在，小于0不存在
     */
    public static boolean verifyBoolean(String tableName, String key, Object value) {
        if (StrUtil.isNotBlank(tableName)) {
            try {
                Object[] objects = ArrayUtil.isArray(value) ? ArrayUtil.cast(Object.class, value) : new Object[]{value};
                List<Object> dataExistList = SpringUtil.getBean(OnlyOneMapper.class)
                        .dataExist(tableName, StrUtil.toUnderlineCase(key), objects);
                return dataExistList.size() == 0;
            } catch (Exception e) {
                log.error("数据库唯一性校验异常", e);
                throw new GlobalException("数据库唯一性校验异常", e);
            }
        }
        return true;
    }

}
